package service

import (
    "context"
    "gitee.com/WisdomClassroom/DisciplineStruct/glb"
    "gitee.com/WisdomClassroom/core"
    "gitee.com/WisdomClassroom/core/models"
    "gitee.com/WisdomClassroom/core/protobufs/v1/pb"
    "github.com/jinzhu/gorm"
)

func (s *Service) ListDiscipline(_ context.Context, in *pb.ListDisciplineRequest) (*pb.ListDisciplineResponse, error) {
    token := core.NewToken()
    err := token.UnpackToken(in.AuthToken, &core.FlagTokenCert)
    if err != nil {
        return &pb.ListDisciplineResponse{Status: &pb.ResponseStatus{
            Code: pb.ResponseStatusCode_NotAuth, Error: err.Error(),
        },}, nil
    }

    var listDsplnRespUnits []*pb.ListDisciplineResponseUnit

    // 读取所有专业
    var disciplines []models.DisciplineModel
    err = glb.DB.Scopes(notDeleted).Find(&disciplines).Error
    if err == nil {
        var collegeDsplnBinds []models.CollegeDisciplineBindModel
        err = glb.DB.Scopes(notDeleted).Find(&collegeDsplnBinds).Error
        if err != nil {
            glb.Logger.Error(err.Error())
            return listDisciplineRespSvrErr, nil
        }

        var dsplnMngrBinds []models.DisciplineManagerBindModel
        err = glb.DB.Scopes(notDeleted).Find(&dsplnMngrBinds).Error
        if err != nil && err != gorm.ErrRecordNotFound {
            glb.Logger.Error(err.Error())
            return listDisciplineRespSvrErr, nil
        }

        listDsplnRespUnitsMap := make(map[string]*pb.ListDisciplineResponseUnit)

        for _, discipline := range disciplines {
            listDsplnRespUnitsMap[discipline.UUID] = &pb.ListDisciplineResponseUnit{
                UUID:        discipline.UUID,
                Name:        discipline.Name,
                Description: discipline.Description,
            }
        }
        for _, collegeDsplnBind := range collegeDsplnBinds {
            listDsplnRespUnitsMap[collegeDsplnBind.DisciplineUUID].CollegeUUID = collegeDsplnBind.CollegeUUID
        }
        for _, dsplnMngrBind := range dsplnMngrBinds {
            listDsplnRespUnitsMap[dsplnMngrBind.DisciplineUUID].ManagerUUID = append(listDsplnRespUnitsMap[dsplnMngrBind.DisciplineUUID].ManagerUUID, dsplnMngrBind.ManagerUUID)
        }

        for _, listDsplnRespUnit := range listDsplnRespUnitsMap {
            listDsplnRespUnits = append(listDsplnRespUnits, listDsplnRespUnit)
        }
    } else if err != gorm.ErrRecordNotFound {
        glb.Logger.Error(err.Error())
        return listDisciplineRespSvrErr, nil
    }

    return &pb.ListDisciplineResponse{
        Status:      &pb.ResponseStatus{Code: pb.ResponseStatusCode_Suc},
        Disciplines: listDsplnRespUnits,
    }, nil
}
